package com.carrie.service;

import com.carrie.mapper.UserMapper;
import com.carrie.model.entity.Users;
import com.carrie.tools.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

/**
 * @author XuHaiLong
 * @since 2025/4/13 21:42
 * 根据给定的用户名加载用户的详细信息（UserDetails 对象），用于 Spring Security 的用户认证流程。
 *异常处理：当没有找到匹配的用户时，都会抛出 UsernameNotFoundException 相关的异常，以此告知 Spring Security 认证失败。
 *助 UserMapper 从数据库中查询用户信息。UserMapper 一般是使用 MyBatis 或者其他持久化框架定义的接口，findByUsername
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
   private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<Users> userEntityOptional = userMapper.selectUserByUsername(username);
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        if (userEntityOptional.isEmpty()) {
            LogUtils.info("没有找到当前用户");
            throw  new UsernameNotFoundException("没有找到当前用户");
        }
        Users user = userEntityOptional.get();
        if(user.getEnabled()){
            System.out.println(user.getUsername()+"允许对/api下的接口进行访问");
            authorities.add(()->"API");
            }
        return new User(user.getUsername(),user.getPassword(), authorities);
    }
}
